//
//  AddPlayerTableViewCell.swift
//  FootballDataRecord
//
//  Created by Xx Jiang on 2020/1/6.
//  Copyright © 2020 Xx Jiang. All rights reserved.
//

import UIKit

typealias insertPlayerBlock = (_ model:PlayerModel)->()

class AddPlayerTableViewCell: UITableViewCell {
    @IBOutlet weak var cellIndex: UILabel!
    @IBOutlet weak var playerName: UITextField!
    @IBOutlet weak var playerNumber: UITextField!
    @IBOutlet weak var deleteButton: UIButton!
    
    var matchModel:MatchModel?
    var insertBlock:insertPlayerBlock?
    var indexP:NSIndexPath? {
        didSet{
            if self.indexP?.section == 0 {
                playerModel.playerType = "0"
            }else{
                playerModel.playerType = "1"
            }
        }
    }
    var playerModel = PlayerModel()
    var teamModel:TeamModel?
    override func awakeFromNib() {
        super.awakeFromNib()
        let placeHolder = UILabel()
        placeHolder.text = "号码"
        placeHolder.textColor = .lightGray
        placeHolder.font = UIFont.systemFont(ofSize: 14)
        playerNumber.addSubview(placeHolder)
        playerNumber.setValue(placeHolder, forKey: "_placeholderLabel")
        let placeHolder2 = UILabel()
        placeHolder2.text = "球员姓名（选填）"
        placeHolder2.textColor = .lightGray
        placeHolder2.font = UIFont.systemFont(ofSize: 14)

        playerName.addSubview(placeHolder2)
        playerName.setValue(placeHolder2, forKey: "_placeholderLabel")
        deleteButton.isHidden = true
    }
    
    
    
    func setCell(model:PlayerModel){
        playerModel = model
        playerNumber.text = playerModel.playerNum
        playerName.text = playerModel.playerName
    }
    
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
    }
    
}



extension AddPlayerTableViewCell:UITextFieldDelegate{
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text!.count == 0 {
            return true;
        }
        weak  var  __weakSelf = self
        if textField == playerNumber {
            if  DYStringIsEmpty(value: playerModel.playerID as AnyObject?)  {
                playerModel.playerNum = textField.text
                playerModel.playerID  = "\(teamModel!.teamID!)" + "_" + "\(textField.text!)"
                if DYStringIsEmpty(value: playerModel.playerName as AnyObject) {
                    playerModel.playerName = "球员\(playerModel.playerNum!)"
                    self.playerName.placeholder = playerModel.playerName
                }
            }
            
            let sql = "select * from \(playerTableName) where \(DHPlayerID) = \"\(playerModel.playerID!)\" "
            DHDataBaseOperate.searchDatasFromDB(sqlString: sql) { (result) in
                if result is FMResultSet {
                               let rs = result as! FMResultSet
                               while rs.next() {
                                    print("重复主键")
                                Toast.makeText(__weakSelf!.findViewController()?.view, message: "❌重复球员编号", afterHideTime: 1.5)
                                __weakSelf?.playerNumber.text = nil
                                __weakSelf?.playerName.placeholder = "球员姓名（选填）"
                                __weakSelf?.playerModel = PlayerModel()
                                return
                               }
                               rs.close()
                           }
            }
            
            
            DHDataBaseOperate.insertModelToDB(model: playerModel) { (rs) in
                if rs.isEqual(1) {
                    print("插入球员成功")
                    DispatchQueue.main.async {
                        self.updateTeamPlayerCount()
                        let playerMatchData = MatchDataModel()
                        let matchDataId = "\(self.matchModel?.matchId ?? "")_player_\(self.playerModel.playerID ?? "")"
                        playerMatchData.matchDataID = matchDataId
                        DHDataBaseOperate.insertModelToDB(model: playerMatchData) { (result) in
                            if result.isEqual(1){
                                print("插入球员数据表成功")
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "insertPlayerModelSuccess"), object: nil, userInfo: ["model":self.playerModel])
                                
                                self.playerModel.playerMatchDataID = playerMatchData.matchDataID
                                DispatchQueue.main.async {
                                    DHDataBaseOperate.changeValuesWithModel(model: self.playerModel, keys: ["mainKey":DHPlayerID,"valueKey":DHPlayerMatchDataID]) { (rs) in
                                        if rs.isEqual(1){
                                            print("修改数据成功")
                                            
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if __weakSelf?.insertBlock != nil {
                        __weakSelf?.insertBlock!(__weakSelf!.playerModel)
                    }
                }
            }
        }else{
            if DYStringIsEmpty(value: playerModel.playerID as AnyObject) {
                playerModel.playerName = playerName.text
            }else{
                if playerName.text!.count > 0{
                    playerModel.playerName = playerName.text
                }else{
                    if DYStringIsEmpty(value: playerModel.playerName as AnyObject) {
                        playerModel.playerName = "球员\(playerModel.playerNum!)"
                    }
                }
                DHDataBaseOperate.changeValuesWithModel(model: playerModel, keys: ["mainKey":DHPlayerID,"valueKey":DHPlayerName]) { (rs) in
                    if rs.isEqual(1) {
                        if __weakSelf?.insertBlock != nil {
                            __weakSelf?.insertBlock!(__weakSelf!.playerModel)
                        }
                        
                        if DYStringIsEmpty(value: self.playerModel.playerMatchDataID as AnyObject){
                            DispatchQueue.main.async {
                                self.updateTeamPlayerCount()
                                let playerMatchData = MatchDataModel()
                                 let matchDataId = "\(self.matchModel?.matchId ?? "")_player_\(self.playerModel.playerID ?? "")"
                                playerMatchData.matchDataID = matchDataId
                                DHDataBaseOperate.insertModelToDB(model: playerMatchData) { (result) in
                                    if result.isEqual(1){
                                        print("插入球员数据表成功")
                                        self.playerModel.playerMatchDataID = playerMatchData.matchDataID
                                        DispatchQueue.main.async {
                                            DHDataBaseOperate.changeValuesWithModel(model: self.playerModel, keys: ["mainKey":DHPlayerID,"valueKey":DHPlayerMatchDataID]) { (rs) in
                                                if rs.isEqual(1){
                                                    print("修改数据成功")
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return true
    }
    
    
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if playerNumber.text!.count > 0{
            
            if "\(teamModel!.teamID! )"+"_"+"\(playerNumber.text!)" == playerModel.playerID {
                Toast.makeText(self.findViewController()?.view, message: "不能修改球员编号", afterHideTime: 1.5)
                return false
            }
            
            
            PlayerModel.getPlayerModelWithPlayerID(playerId: "\(teamModel!.teamID! )"+"_"+"\(playerNumber.text!)") { (rs) in
                if rs is PlayerModel {
                    let model = rs as! PlayerModel
                    self.playerModel = model
                    DispatchQueue.main.async {
                        if textField == self.playerNumber{
                            textField.resignFirstResponder()
                        }
                    }
                }
            }
        }
        return true
    }
    
    
    func updateTeamPlayerCount(){
        let teamodel = TeamModel.getTeamModelWithTeamID(teamId: teamModel!.teamID!)
        teamodel.teamPlayerCount  = NSNumber.init(value: (teamodel.teamPlayerCount!.intValue + 1))
        if indexP?.section == 0 {
            teamodel.shoufaCount  = NSNumber.init(value: (teamodel.shoufaCount!.intValue + 1))
        }else{
            teamodel.tibuCount  = NSNumber.init(value: (teamodel.tibuCount!.intValue + 1))
        }
        DHDataBaseOperate.changeValuesWithModel(model: teamodel, keys: ["mainKey":DHTeamID,"valueKey":[DHTeamShouFaPlayerCount,DHTeamTiBuPlayerCount,DHTeamPlayerCount]]) { (rs) in
            if rs.isEqual(1) {
                print("球员数量修改成功")
            }
        }
    }
}
